<template>
  <el-form ref="form" :model="form" :rules="rules" :hide-required-asterisk="true" label-position="left" style="margin:0 20px;">
    <el-form-item :label="$t('对象名称')" :label-width="formLabelWidth" prop="name">
      <el-input v-emoji size='small' v-model="form.name" ref="name" autocomplete="off" style="width:430px;" @input="updateView($event)"></el-input>
    </el-form-item>
    <el-form-item :label="$t('类型')" :label-width="formLabelWidth">
      <el-radio-group v-model="form.time_type" :disabled="type_info === '编辑'">
        <el-radio label="0" class="timeDay">{{$t('固定日期')}}</el-radio>
        <el-radio label="1" class="timeWeek">{{$t('每周固定循环')}}</el-radio>
        <el-radio label="2" class="timeMonth">{{$t('每月固定循环')}}</el-radio>
      </el-radio-group>
    </el-form-item>

    <!-- ICMP -->
    <div v-if="form.time_type === '0'">
      <el-form-item :label="$t('时间范围')" :label-width="formLabelWidth" prop="timeZeroRange">
        <el-date-picker size='small' v-model="form.timeZeroRange" type="datetimerange" class="timeRange" popper-class="timeEditWeekdays" clearable :range-separator="$t('至')" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" value-format="yyyy-MM-dd HH:mm:ss" style="width:430px;">
        </el-date-picker>
      </el-form-item>
    </div>

    <div v-if="form.time_type === '1'">
      <el-form-item :label="$t('时间范围')" :label-width="formLabelWidth" prop="timeOneRange">
        <el-time-picker size='small' is-range v-model="form.timeOneRange" class="timeRange" key="timeOneRange" popper-class="timeEditWeekdays" @input="updateView($event)" :range-separator="$t('至')" :start-placeholder="$t('开始时间')" :end-placeholder="$t('结束时间')" :placeholder="$t('选择时间范围')" value-format="HH:mm:ss" style="width:430px;">
        </el-time-picker>
      </el-form-item>
      <el-form-item :label="$t('按周循环')" :label-width="formLabelWidth" prop="weekdays">
        <el-select v-model="form.weekdays" ref="weekdays" key="weekdays" multiple clearable collapse-tags filterable @change="changeSelect" size='small' style="width:430px;">
          <div class="selectBox">
            <el-checkbox v-model="checked" :indeterminate="isIndeterminate" @change='selectAll' class="weekdaysAll">{{$t('全选')}}</el-checkbox>
            <el-link :underline="false" @click='selectRe' class="weekdaysInvert" style="line-height: 19px;padding-left:20px;">{{$t('反选')}}</el-link>
          </div>
          <el-option v-for="item in weekdaysList" :key="item.lable" :label="$t(item.value)" :value="item.lable">
          </el-option>
        </el-select>
      </el-form-item>
    </div>

    <div v-if="form.time_type === '2'">
      <el-form-item :label="$t('时间范围')" :label-width="formLabelWidth" prop="timeTwoRange">
        <el-time-picker size='small' is-range v-model="form.timeTwoRange" class="timeRange" key="timeTwoRange" @input="updateView($event)" popper-class="timeEditWeekdays" :range-separator="$t('至')" :start-placeholder="$t('开始时间')" :end-placeholder="$t('结束时间')" :placeholder="$t('选择时间范围')" value-format="HH:mm:ss" style="width:430px;">
        </el-time-picker>
      </el-form-item>
      <el-form-item :label="$t('按月循环')" :label-width="formLabelWidth" prop="monthdays">
        <el-select v-model="form.monthdays" ref="monthdays" key="monthdays" multiple clearable collapse-tags filterable @change="changeSelectMonthdays" size='small' style="width:430px;">
          <div class="selectBox">
            <el-checkbox v-model="checkedMonthdays" :indeterminate="isIndeterminateMonthdays" @change='selectAllMonthdays' class="timeTwoRangeAll">{{$t('全选')}}</el-checkbox>
            <el-link :underline="false" @click='selectReMonthdays' class="timeTwoRangeInvert" style="line-height: 19px;padding-left:20px;">{{$t('反选')}}</el-link>
          </div>
          <el-option v-for="item in monthdaysList" :key="item.lable" :label="$t(item.value)" :value="item.lable">
          </el-option>
        </el-select>
      </el-form-item>
    </div>

  </el-form>

</template>

<script>
import timeArray from './timeArray'
import { inputClass } from '@/utils/input-class.js'
export default {
  inject: ['reload'],
  props: [
    'dialogFormVisible',
    'type_info',
    'edit_form'
  ],
  name: 'TimeEdit',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入对象名称')))
      } else {
        callback()
      }
    }
    var validateRange = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('请输入时间范围')))
      } else {
        callback()
      }
    }
    return {
      old_name: {},
      old_desc: '',
      weekdaysList: timeArray.weekdays,
      monthdaysList: timeArray.monthdays,
      weekdaysLable: ['1', '2', '3', '4', '5', '6', '7'],
      monthdaysLable: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
      checked: false,
      isIndeterminate: false,
      checkedMonthdays: false,
      isIndeterminateMonthdays: false,
      form: {
        time_type: '0',
        name: '',
        timeZeroRange: null,
        timeOneRange: null,
        timeTwoRange: null,
        weekdays: [],
        monthdays: []
      },
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        timeZeroRange: [{ required: false, validator: validateRange, trigger: 'change' }],
        timeOneRange: [{ required: false, validator: validateRange, trigger: 'change' }],
        timeTwoRange: [{ required: false, validator: validateRange, trigger: 'change' }],
        weekdays: [{ required: true, message: this.$t('请输入按周循环'), trigger: 'change' }],
        monthdays: [{ required: true, message: this.$t('请输入按月循环'), trigger: 'change' }]
      },
      formLabelWidth: '100px'
    }
  },
  watch: {
    edit_form: {
      handler (val) {
        if (this.type_info === '编辑') {
          this.form = Object.assign(this.form, val)
          this.old_name = val.name
          this.old_desc = val.desc
          if (val.time_type === '0') {
            this.form.timeZeroRange = [val.starttime, val.endtime]
          } else if (val.time_type === '1') {
            this.form.timeOneRange = [val.starttime, val.endtime]
            this.form.weekdays = []
            for (let item of val.weekdays) {
              this.form.weekdays.push(String(item))
            }
            this.changeSelect(this.form.weekdays)
          } else if (val.time_type === '2') {
            this.form.timeTwoRange = [val.starttime, val.endtime]
            this.form.monthdays = []
            for (let item of val.monthdays) {
              this.form.monthdays.push(String(item))
            }
            this.changeSelectMonthdays(this.form.monthdays)
          }
        }
      },
      immediate: true
    },
    'form.time_type': {
      handler (newVal) {
        switch (newVal) {
          case '1':
            this.$nextTick(() => {
              const data = ['weekdays']
              inputClass(this.$refs, data)
            })
            break
          case '2':
            this.$nextTick(() => {
              const data = ['monthdays']
              inputClass(this.$refs, data)
            })
            break
        }
      },
      immediate: true
    }
  },
  methods: {
    inputChange (type) {
      if (type === 'account') {
        this.form.account = this.form.account.replace(/([\u4e00-\u9fa5])|(\s)|[^\d\w]/g, '')
      } else {
        this.form.mobile = this.form.mobile.replace(/[^\d]/g, '')
      }
    },
    // 发送form表单数据到父组件
    send_form () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let childForm = {}
          childForm = this.form
          if (!childForm.name) {
            this.$messages.error(this.$t('请输入名称'))
            return
          }
          if (this.type_info === '编辑') {
            childForm.old_name = this.old_name
          }
          this.$emit('childForm', childForm)
        }
      })
    },
    selectAll () {
      this.form.weekdays = []
      if (this.checked) {
        this.weekdaysList.forEach((item) => {
          this.form.weekdays.push(item.lable)
        })
      } else {
        this.form.weekdays = []
      }
      this.isIndeterminate = false
    },
    selectRe () {
      let check_array = JSON.parse(JSON.stringify(this.form.weekdays))
      this.form.weekdays = this.weekdaysLable.filter((x) => !check_array.some((item) => x === item))
      this.changeSelect(this.form.weekdays)
    },
    changeSelect (val) {
      let checkedCount = val.length
      this.checked = checkedCount === this.weekdaysList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.weekdaysList.length
    },
    selectAllMonthdays () {
      this.form.monthdays = []
      if (this.checkedMonthdays) {
        this.monthdaysList.forEach((item) => {
          this.form.monthdays.push(item.lable)
        })
      } else {
        this.form.monthdays = []
      }
      this.isIndeterminateMonthdays = false
    },
    selectReMonthdays () {
      let check_array = JSON.parse(JSON.stringify(this.form.monthdays))
      this.form.monthdays = this.monthdaysLable.filter((x) => !check_array.some((item) => x === item))
      this.changeSelectMonthdays(this.form.monthdays)
    },
    changeSelectMonthdays (val) {
      let checkedCount = val.length
      this.checkedMonthdays = checkedCount === this.monthdaysList.length
      this.isIndeterminateMonthdays = checkedCount > 0 && checkedCount < this.monthdaysList.length
    },
    updateView (e) {
      this.$forceUpdate()
    },
    close () {
      this.checked = false
      this.isIndeterminate = false
      this.checkedMonthdays = false
      this.isIndeterminateMonthdays = false
      this.form = {
        time_type: '0',
        name: '',
        timeZeroRange: null,
        timeOneRange: null,
        timeTwoRange: null,
        weekdays: [],
        monthdays: []
      }
      this.old_name = {}
      this.old_desc = ''
      this.$refs.form.resetFields()
    },
    classRef () {
      const data = ['name']
      inputClass(this.$refs, data)
    }
  }
}
</script>

<style scoped>
.tools_box {
  text-align: left;
}
.circle {
  padding: 5px;
}
.selectBox {
  padding: 0 20px;
}
</style>
<style lang='scss'>
.timeEditWeekdays {
  .el-time-panel__btn.cancel {
    float: right;
  }
}
.timeEditWeekdays {
  .el-button.el-picker-panel__link-btn.el-button--text.el-button--mini {
    float: right;
    margin: 0 15px;
  }
}
</style>
